package cn.com.fattiger.framework.cms.admin.common.service.impl;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import cn.com.fattiger.framework.cms.admin.common.service.TemplateService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.utility.StringUtil;

/**
 * Created by Administrator on 2016/1/8.
 */
@Service
public class TemplateServiceImpl implements TemplateService {

    @Autowired
    private Configuration templateConfiguration;

    @Autowired
    private FreeMarkerConfigurer configurer;

    @Override
    public void templateToFile(String template, Map<String, Object> data, String output) {
        Writer out = new OutputStreamWriter(System.out);
        try {
            Template temp = configurer.getConfiguration().getTemplate(template);
            if (null != StringUtil.emptyToNull(output)) {
                out = new OutputStreamWriter(new FileOutputStream(output), "utf-8");
            }
            temp.process(data, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public String templateToString(String template, Map<String, Object> data) throws Exception {
        StringWriter out = new StringWriter();
        try {
            Template temp = templateConfiguration.getTemplate(template);
            temp.process(data, out);
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


}
